package com.lemo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 性能监控
 */
public class PermHandlerInterceptor extends HandlerInterceptorAdapter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass().getCanonicalName());
    //Spring提供的一个命名的ThreadLocal实现
    private NamedThreadLocal<Long> currentTimeThreadLocal = new NamedThreadLocal<>("startTime");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        PermIgnore annotation;
        if (handler instanceof HandlerMethod){
            annotation = ((HandlerMethod) handler).getMethodAnnotation(PermIgnore.class);
        }else {
            return true;
        }
        //如果有PermIgnore注解，则不性能检测
        if (annotation != null) {
            return true;
        }
        long startTime = System.currentTimeMillis();
        currentTimeThreadLocal.set(startTime);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        PermIgnore annotation;
        if (handler instanceof HandlerMethod){
            annotation = ((HandlerMethod) handler).getMethodAnnotation(PermIgnore.class);
        }else {
            return;
        }
        //如果有PermIgnore注解，则不性能检测
        if (annotation != null) {
            return;
        }
        long endTime = System.currentTimeMillis();
        long startTime = currentTimeThreadLocal.get();
        long useTime = endTime - startTime;
        if (useTime > 1) {
            logger.info("[{}] use {} ms]", request.getRequestURI(), useTime);
        }
    }
}
